package com.sinotrans.auth.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.util.OAuth2Utils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sinotrans.auth.entity.UserEntity;
import com.sinotrans.auth.repository.UserRepository;
import com.sinotrans.auth.service.SecurityService;
import com.sinotrans.common.security.AuthEntity;
import com.sinotrans.common.util.ServletUtil;

@Service
public class SecurityServiceImpl implements SecurityService, UserDetailsService {
	final static Logger logger = LoggerFactory.getLogger(SecurityServiceImpl.class);

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		HttpServletRequest request = ServletUtil.getRequest();
		String grantType = request.getParameter(OAuth2Utils.GRANT_TYPE);
		String password = request.getParameter("password");
		//
		AuthEntity authEntity = null;
		try {
			if ("password".equalsIgnoreCase(grantType)) {
				authEntity = login(username, password);
			} else {
				UserEntity userEntity = queryUserByUsername(username);
				authEntity = userToAuth(userEntity);
			}
		} finally {
			logger.error("loadUserByUsername error");
		}
		//
		List<SimpleGrantedAuthority> roleList = new ArrayList<SimpleGrantedAuthority>();
		if (authEntity.getRls() != null) {
			for (String role : authEntity.getRls()) {
				roleList.add(new SimpleGrantedAuthority(role));
			}
		}
		if (StringUtils.isEmpty(password)) {
			password = "";
		}
		User user = new User(username, passwordEncoder.encode(password), roleList);
		return user;
	}

	// TODO 角色查询待实现
	private AuthEntity userToAuth(UserEntity user) {
		AuthEntity authEntity = new AuthEntity();
		authEntity.setUid(user.getId());
		authEntity.setUn(user.getUsername());
		List<String> roles = new ArrayList<String>();
		//
//		roles.add("role1");
//		roles.add("role2");
		authEntity.setRls(roles);
		return authEntity;
	}

	// TODO 密码加密
	@Override
	public String encryptPassword(String password) throws UsernameNotFoundException {
		return password;
	}

	@Override
	public AuthEntity login(@NotNull String username, @NotNull String password) throws UsernameNotFoundException {
		UserEntity user = queryUserByUsername(username);
		String encryptPassword = encryptPassword(password);
		if (!encryptPassword.equalsIgnoreCase(user.getPassword())) {
			throw new UsernameNotFoundException("用户或密码错误");
		}
		return userToAuth(user);
	}

	private UserEntity queryUserByUsername(String username) throws UsernameNotFoundException {
		UserEntity user = new UserEntity();
		user.setUsername(username);
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<UserEntity>();
		queryWrapper.setEntity(user);
		user = userRepository.getOne(queryWrapper);
		if (user == null) {
			throw new UsernameNotFoundException("用户或密码错误");
		}
		return user;
	}

}
